package BinaryTree;
import java.util.*;

/**
 * User:
 * Date:2022-10-09
 * Time:15:59
 */
public class TestBinaryTree1 {
    public class TreeNode1 {
       int val;
        TestBinaryTree1.TreeNode1 left;
        TestBinaryTree1.TreeNode1 right;

        TreeNode1() {

        }

        TreeNode1(int val) {

            this.val = val;
        }

        TreeNode1(int val, TestBinaryTree1.TreeNode1 left, TestBinaryTree1.TreeNode1 right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    /**
     * 二叉树的前序非递归实现
     * @param root
     * @return
     */
    public List<Integer> preorderNor(TreeNode1 root){
        List<Integer> ret = new ArrayList<>();
        TreeNode1 cur = root;
        Stack<TreeNode1> stack = new Stack<>();

        while (cur!=null || !stack.isEmpty()){//左边不为空的情况下看栈是否为空

            while (cur !=  null){//一直往左走看左边是否为空
                stack.push(cur);
                System.out.println(cur.val+" ");
                ret.add(cur.val);
                cur = cur.left;
            }
            TreeNode1 top = stack.pop();
            cur = cur.right;
        }
        return  ret;
    }

    /**
     * 二叉树的中序非递归实现
     * @param
     */
    public List<Integer> inorderTraversalNor(TreeNode1 root) {
        List<Integer> ret = new ArrayList<>();
        TreeNode1 cur = root;
        Stack<TreeNode1> stack = new Stack<>();
        while (cur != null || !stack.isEmpty()) {
            while (cur != null) {
                stack.push(cur);
                cur = cur.left;
            }
            TreeNode1 top = stack.pop();
            ret.add(top.val);
            cur = top.right;
        }
        return ret;
    }

    /**
     * 二叉树的后序非递归实现
     * @param
     */
    public List<Integer> postorderTraversalNor(TreeNode1 root) {
        List<Integer> ret = new ArrayList<>();
        TreeNode1 cur = root;
        Stack<TreeNode1> stack = new Stack<>();
        TreeNode1 prev = null;

        while (cur != null || !stack.isEmpty()) {
            while (cur != null) {
                stack.push(cur);
                cur = cur.left;
            }
            TreeNode1 top = stack.peek();
            if (top.right == null
                    || top.right == prev) {
                ret.add(top.val);
                stack.pop();
                prev = top;
            } else {
                cur = top.right;
            }
        }
        return ret;
    }

    public static void main(String[] args) {

    }

}
